package com.cloud.pikachu.dingtalk.service.token;


import com.alibaba.fastjson.JSONObject;
import com.cloud.pikachu.dingtalk.api.JsApiTickenAPI;
import com.cloud.pikachu.dingtalk.bean.JsApiTicket;
import com.cloud.pikachu.dingtalk.constant.DingtalkConstant;
import com.cloud.pikachu.dingtalk.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * jsApiTicken 计算service
 * 因为 js api每个应用会分配一个 , 并且没请求一次生成一个2小时内有效的值 , 为了集群化部署时保证数据的可用性,
 * 将数据保存在 公共缓存中redis中 , 保存的内容格式为 redis的key值为 jsApi : {ticket : XXXXX , cerateTime : XXXXX}
 * @author ABug
 */
@Service
public class JsApiTickenService {
    private static final Logger logger = LoggerFactory.getLogger(AccessTokenService.class);

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AccessTokenService accessTokenService;

    /**
     * 思路建设 : 怎么实现多个服务同时调用redis同步更新数据  保证redis中的同步的数据不会被其它服务占用
     * 定时任务模式不太可靠 , 实际业务单台就可以
     * 定义两个变量一个是jsApiTicken值  jsApiTicken的更新锁
     */
    /**
     * 用用获取token
     * @return
     */
    public String getJsApiTicken(){
        String jsApiTickenValue = (String) redisUtil.get("jsApiTicken");

        if(jsApiTickenValue == null ){
            /**
             * 生成新的 jsApiTicken 值
             */
            JsApiTicket jsApiTicket = JsApiTickenAPI.getJsApiTicket(accessTokenService.getAccessToken());

            if(jsApiTicket == null || jsApiTicket.getErrcode() != 0){
                logger.error("获取jsApiTicken失败，钉钉返回数据["+ JSONObject.toJSONString(jsApiTicket) +"]");
            }else{
                redisUtil.set(DingtalkConstant.REDIS_JSAPITICKEN_KEY , jsApiTicket.getTicket() , DingtalkConstant.REDIS_JSAPITICKEN_TIME);
                jsApiTickenValue = jsApiTicket.getTicket();
            }
        }
        logger.info("jsApiTicken值 = " + jsApiTickenValue);
        return jsApiTickenValue;
    }

    /**
     * 强制刷新 jsApiTicken
     * @return
     */
    public String updateJsApiTicken(){
        JsApiTicket jsApiTicket = JsApiTickenAPI.getJsApiTicket(accessTokenService.getAccessToken());

        if(jsApiTicket == null || jsApiTicket.getErrcode() != 0){
            logger.error("获取jsApiTicken失败，钉钉返回数据["+ JSONObject.toJSONString(jsApiTicket) +"]");
            return null;
        }else{
            redisUtil.set(DingtalkConstant.REDIS_JSAPITICKEN_KEY , jsApiTicket.getTicket() , DingtalkConstant.REDIS_JSAPITICKEN_TIME);
            return jsApiTicket.getTicket();
        }
    }

}
